package com.zhouheng.springbootmultithreading.tuling.hashMap.threadpool;


import com.zhouheng.springbootmultithreading.tuling.hashMap.MonkeyRejectedExecutionHandler;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 阿里不推荐使用java的Executors线程池
 * Executors都是用的ThreadPoolExecutor
 */
public class ThreadPoolDemo {

    public static void main(String[] args) {
        /**
         * 快
         * SynchronousQueue队列里只有1个，来一个任务，就创建一个非核心线程去执行，所以需要创建100个线程；
         * 但是如果线程里的任务执行很快，可能会出现线程互用，例如线程1先把任务1执行完了，任务10来了，线程1就也会去执行任务10
          */
        ExecutorService executorService1 = Executors.newCachedThreadPool();
        /**
         * 慢
         * 只有固定数量的核心线程，没有非核心线程
         */
        ExecutorService executorService2 = Executors.newFixedThreadPool(10);
        /**
         * 最慢
         * 只有一个核心线程，没有非核心线程
         */
        ExecutorService executorService3 = Executors.newSingleThreadExecutor();

        // 自定义线程
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 20,
                0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(10), new MonkeyRejectedExecutionHandler());

        for (int i = 1; i <= 100; i++) {
//            executorService1.execute(new MyTask(i));
//            executorService2.execute(new MyTask(i));
//            executorService3.execute(new MyTask(i));
            threadPoolExecutor.execute(new MyTask(i));
        }

    }
}

